require 'MVVM.Sources.View.Adaptor'

LoopScrollRectAdaptor = class('LoopScrollRectAdaptor', Adaptor)

function LoopScrollRectAdaptor:ctor(gameObject, propertyName, binder, childFuncPropertyName, centerItemIndex)
    self.component = gameObject:GetComponent('UnityEngine.UI.LoopScrollRect')
    self.startPos = 0

    if centerItemIndex then
        binder:Add(centerItemIndex,function(oldValue,newValue)
            if newValue == nil then
                return
            end
            self.startPos = newValue
        end)
    end

    binder:RegisterEvent(function(viewModel, property)
        self.component.provideDataCallback = function(trans,index)
                local view = GetLuaObject(trans)
                if view then
                    view.CellIndex = index
                    local childModel = property.Value[index + 1]
                    if childModel then
                        view.LoopScrollIndex = FrameNum == self.ActiveFrameNum and index +1 or -1
                        view:Set_BindingContext(childModel)
                        if childModel[childFuncPropertyName] then
                            childModel[childFuncPropertyName](childModel)
                        end
                    end
                end
            end
    end, function()
        self.component.provideDataCallback = nil
    end, propertyName)
    self:BindProperty(propertyName, binder)
end

function LoopScrollRectAdaptor:OnViewModelValueChanged(oldValue, newValue)
    if newValue == nil then
        return
    end
    self.component.totalCount = #newValue
    self.ActiveFrameNum = FrameNum
    self.component:RefillCells(self.startPos)
end